import { App } from 'vue'
import { logger, eventBus } from '@/instance'

export default {
  install(app: App, opt: any) {
    app.directive('drag', {
      /**
       * 注册拖拽相关事件并转发到evenBus
       * 是否需要用mouse事件模拟drag事件?
       * @param {*} el
       * @param {*} binding
       */
      mounted(el: any, binding) {
        const prefix = binding.value.prefix
        logger.log('plugins/dnd', 'drag mounted', arguments)
        el.setAttribute('draggable', binding.value.draggable || 'true')
        ;[
          'dragstart',
          'dragenter',
          'dragleave',
          'dragover',
          'drag',
          'dragend',
        ].forEach((t) => {
          el['on' + t] = (e: Event) => {
            t !== 'dragstart' && e.preventDefault()
            eventBus.emit(`${prefix}-${t}`, { data: binding.value.data, e })
          }
        })
      },
      beforeUnmount(el: any) {
        logger.log('plugins/dnd', 'drag before unmounted', arguments)
        ;[
          'dragstart',
          'dragenter',
          'dragleave',
          'dragover',
          'drag',
          'dragend',
        ].forEach((t) => {
          el['on' + t] = null
        })
      },
    })
    app.directive('drop', {
      mounted(el: HTMLElement, binding) {
        logger.log('plugins/dnd', 'drop mounted', arguments)
        const prefix = binding.value.prefix
        el.ondrop = (e: Event) => {
          e.preventDefault()
          eventBus.emit(`${prefix}-drop`, { data: binding.value.data, e })
        }
      },
      beforeUnmount(el: HTMLElement) {
        logger.log('plugins/dnd', 'drop before unmounted', arguments)
        el.ondrop = null
      },
    })
  },
}
